import os


class PageResponse:

    def __init__(self,conn, requeset_page_name):
        self.conn = conn
        self.page_name = requeset_page_name
        self._web_path = '/home/dht/our_project'

    def user_login(self):
        pass

    def page_response(self):
        # 发现他不显得原因是他有两个请求，其中一个请求的内容我这里没有处理，导致他一直在等待，所以不显示内容
        # 我这里重启服务端后他判定接受失败，才开始显示的
        if self.page_name[1:] in os.listdir(self._web_path):
            page_content = self.response_head('200')
            # print('找到了网页')
            self.conn.send(page_content)
            with open(self._web_path + self.page_name, 'rb') as f:
                while 1:
                    send_msg = f.read()
                    if not send_msg:
                        break
                    self.conn.send(send_msg)
            # print('消息发送完毕')
        else:
            page_content = self.response_head('404')

            self.conn.send(page_content)

    def response_head(self, code):
        if code == '404':
            page_content = 'HTTP/1.1 404 NOT FOUND\r\nContent-Type: text/html\r\n\r\n<h1>NOT FOUND!</h1>'
            return page_content.encode()
        elif code == '200':
            page_content = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n'
            return page_content.encode()

    def request_is_what(self):
        if 'login' in self.page_name[1:] :
            self.page_login()
        elif 'index' in self.page_name[1:]:
            self.page_response()
        elif 'exit' in self.page_name[1:]:
            self.page_exit()